class User
  include DataMapper::Resource
  storage_names[:default] = "User"
  
  property :id,             Serial
  property :username,       String,        :required => true, :length => 500
  property :hash_password,  String,        :length => 500
  property :salt,           String,        :length => 500
  property :is_admin,       Boolean
  property :is_blocked,     Boolean
  property :can_not_delete, Boolean
  property :description,    Text, 	   :lazy => false
  timestamps :at 

  has 1, :profile

  # Validation
 
  # Property
  cattr_accessor :current_user
  attr_accessor :password_confirmation

  # Property password
  def password
    @password
  end

  # Property password=
  def password=(pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hash_password = User.encrypted_password(self.password, self.salt)
  end

  # Static authenticate function
  def self.authenticate(name, password)
    user = self.find_by_username(name)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hash_password != expected_password
        user = nil
      end
    end
    user
  end

  private
  # Function to encrypt password
  def self.encrypted_password(password, salt)
    string_to_hash = password + "lead" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end

  # Create new salt
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
end
